package com.itgaohe.utils;

import java.nio.ByteBuffer;
import java.util.zip.CRC32;

public class CreateCursorUtil {

    /**
     * 创建普通 cursor 值
     * @param userId 用户 id
     * @return cursor
     */
    public static Long getNormalCursor (Long userId) {
        Long hashUserId = hashTo20BitBinary(userId) ;
        Long cursor = System.currentTimeMillis() ;
        cursor <<= 20 ;
        cursor |= hashUserId ;
        return cursor;
    }

    /**
     * 初始化 cursor 值
     */
    public static Long initCursor() {
        Long cursor = System.currentTimeMillis() ;
        cursor <<= 20 ;
        return cursor ;
    }


    /**
     * 创建博客 cursor
     * @param like 点赞数
     * @param userId 用户 id
     * @return cursor
     */
    public static Long getBlogCursor (Long like,Long userId) {
        Long hashUserId = hashTo10BitBinary(userId) ;
        Long cursor = System.currentTimeMillis() ;
        cursor <<= 10 ;
        cursor |= (like & 0x3FFL) ;
        cursor <<= 10 ;
        cursor |= hashUserId ;
        return cursor ;
    }

    /**
     * 解析修改 cursor 值
     */
    public static Long updateBlogCursor (Long cursor,Long newLike) {
        long timestamp = cursor >>> 20;
        long likeValue =cursor >>> 10;
        long userIdHash = cursor & 0x3FFL ;
        timestamp <<= 10 ;
        cursor |= newLike ;
        cursor <<= 10 ;
        cursor |= userIdHash ;
        return cursor ;
    }

    public static Long hashTo10BitBinary(Long input) {
        CRC32 crc32 = new CRC32();
        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
        buffer.putLong(input);
        crc32.update(buffer.array());
        return crc32.getValue() & 0x3FFL;
    }

    public static Long hashTo20BitBinary(Long input) {

        CRC32 crc32 = new CRC32();
        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
        buffer.putLong(input);
        crc32.update(buffer.array());
        return crc32.getValue() & 0xFFFFFL;
    }

}
